package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

//@RestController
//@RequestMapping("admin/product")
public class FileUpload2Controller {

    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    @Value("${minio.accessKey}")
    private String  accessKey;

    @Value(("${minio.secreKey}"))
    private String secreKey;

    @Value("${minio.bucketName}")
    private String bucketName;

    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception{

        String url = "";

        //构建 minio client
        MinioClient minioClient = MinioClient.builder().endpoint(endpointUrl).credentials(accessKey, secreKey).build();

        //判断桶是不是存在，不存在就创建一个
        boolean isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(isExists){
            System.out.println("bucket is exists..");
        }else{
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        //文件的名称  当前的时间毫秒+随即的UUID字符串
        String fileName = System.currentTimeMillis() + UUID.randomUUID().toString();

        //文件上传
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(),file.getSize(),-1)
                .contentType(file.getContentType())
                .build());

        //构建文件的完整地址
        url = endpointUrl + "/" + bucketName + "/" + fileName;

        return Result.ok(url);


    }

}
